# 老师讲的单链表

class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next = None


class List(object):
    def __init__(self):
        self.head = Node()

        self.length = 0

    def insert(self, pos, data):
        assert pos >= 0 and pos <= self.length

        # Find out the position to insert.
        tmpPtr = self.head
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        # Insert new node
        newNode = Node()

        newNode.data = data
        newNode.next = tmpPtr.next

        tmpPtr.next = newNode
        self.length += 1
    # 为什么我没有用这个函数 页不报错
    # def __len__(self): 注释掉:TypeError: object of type 'List' has no len()
    #     return self.length
    def append(self, data):
        self.insert(self.length, data)

    def remove(self, pos):
        assert pos < self.length

        tmpPtr = self.head
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        if tmpPtr.next is not None:
            delNode = tmpPtr.next#这两句有点混淆
            tmpPtr.next = delNode.next #
            self.length -= 1

    # 干嘛的啊 这个,遍历:生成迭代器
    def foreach(self):
        tmpPtr = self.head.next
        while tmpPtr is not None:
            yield tmpPtr.data
            tmpPtr = tmpPtr.next


if __name__ == "__main__":
    l = List()
    l.append(1)
    l.append(2)
    l.append(3)

    # for x in l:#TypeError: 'List' object is not iterable
    for x in l.foreach():
        print(x)

    print("Insert new data 4")
    l.insert(1, 4)
    for x in l.foreach():
        print(x)

    print("Remove the 2th element")
    l.remove(1)
    for x in l.foreach():
        print(x)

